<template>
  <div class="dashboard">
    <div class="vital-signs-section">
      <h2>生命体征监控</h2>
      <div class="charts-container">
        <VitalsChart 
          :heartRate="vitalsData.heartRate"
          :respiration="vitalsData.respiration"
        />
      </div>
    </div>
    <div class="environment-section">
      <h2>环境数据</h2>
      <div class="env-data-grid">
        <div class="env-card">
          <h3>温度</h3>
          <p>{{ environmentData.temperature }}°C</p>
        </div>
        <div class="env-card">
          <h3>湿度</h3>
          <p>{{ environmentData.humidity }}%</p>
        </div>
        <div class="env-card">
          <h3>光照</h3>
          <p>{{ environmentData.light }} lux</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import VitalsChart from '../components/Dashboard/VitalsChart.vue'

const vitalsData = ref({
  heartRate: [],
  respiration: []
})

const environmentData = ref({
  temperature: 0,
  humidity: 0,
  light: 0
})

let updateInterval: number | null = null

const fetchVitalSigns = async () => {
  try {
    const response = await fetch('/api/vital-signs')
    const data = await response.json()
    vitalsData.value = data
  } catch (error) {
    console.error('获取生命体征数据失败:', error)
  }
}

const fetchEnvironmentData = async () => {
  try {
    const response = await fetch('/api/environment')
    const data = await response.json()
    environmentData.value = data
  } catch (error) {
    console.error('获取环境数据失败:', error)
  }
}

const updateData = () => {
  fetchVitalSigns()
  fetchEnvironmentData()
}

onMounted(() => {
  updateData()
  updateInterval = setInterval(updateData, 5000) // 每5秒更新一次数据
})

onUnmounted(() => {
  if (updateInterval) {
    clearInterval(updateInterval)
  }
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.vital-signs-section,
.environment-section {
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  color: #2c3e50;
  font-size: 1.5rem;
}

.charts-container {
  height: 400px;
}

.env-data-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
}

.env-card {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
}

.env-card h3 {
  color: #6c757d;
  margin-bottom: 10px;
  font-size: 1rem;
}

.env-card p {
  font-size: 1.5rem;
  font-weight: bold;
  color: #2c3e50;
  margin: 0;
}
</style>
